/*
 * This file is part of Cadmium.
 * Copyright (C) 2007-2010 Xavier Clerc.
 *
 * Cadmium is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * Cadmium is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package fr.x9c.cadmium.primitives.graph;

import java.awt.image.BufferedImage;

import fr.x9c.cadmium.kernel.Block;
import fr.x9c.cadmium.kernel.CodeRunner;
import fr.x9c.cadmium.kernel.Fail;
import fr.x9c.cadmium.kernel.Primitive;
import fr.x9c.cadmium.kernel.PrimitiveProvider;
import fr.x9c.cadmium.kernel.Value;

/**
 * This class provides the implementation of 'caml_gr_dump_image' primitive.
 *
 * @author <a href="mailto:cadmium@x9c.fr">Xavier Clerc</a>
 * @version 1.0
 * @since 1.0
 */
@PrimitiveProvider
public final class DumpImage {

    /**
     * No instance of this class.
     */
    private DumpImage() {
    } // end empty constructor

    /**
     * Converts an image into a pixel array.
     * @param ctxt context
     * @param vimg image to convert
     * @return pixel array corresponding to the image
     * @throws Fail.Exception if <i>Graphics</i> module has not been initialized
     */
    @Primitive
    public static Value caml_gr_dump_image(final CodeRunner ctxt,
                                           final Value vimg)
        throws Fail.Exception {
        GraphSlot.checkGraph(ctxt);
        final BufferedImage img = (BufferedImage) vimg.asBlock().asCustom();
        final int width = img.getWidth();
        final int height = img.getHeight();
        final Block res = Block.createBlock(height, 0);
        final int[] pixels = img.getRGB(0, 0, width, height, null, 0, width);
        for (int i = 0; i < height; i++) {
            final Block line = Block.createBlock(width, 0);
            for (int j = 0; j < width; j++) {
                final int v = pixels[j * width + i];
                if ((v & 0xFF000000) != 0) {
                    line.set(j, Value.createFromLong(v & 0x00FFFFFF));
                } else {
                    line.set(j, Value.MINUS_ONE);
                } // end if/else
            } // end for
            res.set(i, Value.createFromBlock(line));
        } // end for
        return Value.createFromBlock(res);
    } // end method 'caml_gr_dump_image(CodeRunner, Value)'

} // end class 'DumpImage'
